<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import { useUserStore } from '../stores/modules/user'
import Graphic from '@arcgis/core/Graphic'
import Point from '@arcgis/core/geometry/Point'
import Polyline from '@arcgis/core/geometry/Polyline'
import { ElMessage, ElMessageBox } from 'element-plus'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import gaodeLayer from '@/utils/GaoDeBaseLayer'
import SketchViewModel from '@arcgis/core/widgets/Sketch/SketchViewModel'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer'

const router = useRouter()
const userStore = useUserStore()

// 图层URL
const buildingLayerUrl =
  'https://services8.arcgis.com/CmXfu09loK81if9H/arcgis/rest/services/GISRouteAnalysis/FeatureServer/0'
const facilitiesLayerUrl =
  'https://services8.arcgis.com/CmXfu09loK81if9H/arcgis/rest/services/GISRouteAnalysis/FeatureServer/1'
const roadsLayerUrl =
  'https://services8.arcgis.com/CmXfu09loK81if9H/arcgis/rest/services/GISRouteAnalysis/FeatureServer/2'

// 图层实例
let buildingLayer: __esri.FeatureLayer | null = null
let facilitiesLayer: __esri.FeatureLayer | null = null
let roadsLayer: __esri.FeatureLayer | null = null

// 地图相关
const mapDiv = ref<HTMLDivElement | null>(null)
const buildingMapDiv = ref<HTMLDivElement>()
const facilitiesMapDiv = ref<HTMLDivElement>()
const roadMapDiv = ref<HTMLDivElement>()
// 修改为普通变量而非 ref
let sketchLayer: __esri.GraphicsLayer | null = null
let mapView: __esri.MapView | null = null
let dialogMapView: __esri.MapView | null = null
let sketchViewModel: __esri.SketchViewModel | null = null
let sketchRoad: __esri.Polyline | null = null
let sketchBuilding: __esri.Point | null = null // 新增建筑物点位对象
let sketchFacility: __esri.Point | null = null // 新增设施点位对象

// 数据列表
const buildingList = ref<any[]>([])
const facilitiesList = ref<any[]>([])
const roadsList = ref<any[]>([])

// 当前选中的标签页
const activeTab = ref('building')

// 当前编辑模式
const currentEditMode = ref('')

// 新增表单数据
const buildingForm = reactive({
  name: '',
  Buildingtype: '',
  description: '',
})

const facilitiesForm = reactive({
  name: '',
  FacilitiesType: '',
  description: '',
})

const roadForm = reactive({
  name: '',
  RoadType: '',
})

// 表单可见性
const buildingDialogVisible = ref(false)
const facilitiesDialogVisible = ref(false)
const roadDialogVisible = ref(false)

buildingLayer = new FeatureLayer({
  url: buildingLayerUrl,
  outFields: ['*'],
})

facilitiesLayer = new FeatureLayer({
  url: facilitiesLayerUrl,
  outFields: ['*'],
})

roadsLayer = new FeatureLayer({
  url: roadsLayerUrl,
  outFields: ['*'],
})
// 初始化地图
const initMap = () => {
  return new Promise<void>((resolve) => {
    if (mapDiv.value) {
      // 创建建筑物图层 - 使用填充样式
      buildingLayer = new FeatureLayer({
        url: buildingLayerUrl,
        outFields: ['*'],
        renderer: {
          type: 'simple',
          symbol: {
            type: 'simple-marker',
            color: [255, 165, 0, 0.6], // 橙色半透明
            outline: {
              color: [255, 140, 0, 1], // 深橙色边框
              width: 2
            }
          }
        } as any,
        popupTemplate: {
          title: '建筑物信息',
          content: [
            {
              type: 'fields',
              fieldInfos: [
                { fieldName: 'name', label: '建筑名称' },
                { fieldName: 'BuildingType', label: '建筑类型' },
                { fieldName: 'OBJECTID', label: 'ID' }
              ]
            }
          ]
        }
      })

      // 创建设施图层 - 使用点样式
      facilitiesLayer = new FeatureLayer({
        url: facilitiesLayerUrl,
        outFields: ['*'],
        renderer: {
          type: 'simple',
          symbol: {
            type: 'simple-marker',
            color: [0, 150, 255, 0.8], // 蓝色
            size: 12,
            outline: {
              color: [0, 100, 200, 1], // 深蓝色边框
              width: 2
            },
            style: 'circle'
          }
        } as any,
        popupTemplate: {
          title: '设施信息',
          content: [
            {
              type: 'fields',
              fieldInfos: [
                { fieldName: 'name', label: '设施名称' },
                { fieldName: 'FacilityType', label: '设施类型' },
                { fieldName: 'OBJECTID', label: 'ID' }
              ]
            }
          ]
        }
      })

      // 创建道路图层 - 使用线样式，根据道路类型设置不同颜色
      roadsLayer = new FeatureLayer({
        url: roadsLayerUrl,
        outFields: ['*'],
        popupEnabled: false,
        renderer: {
          type: 'unique-value',
          field: 'RoadType',
          defaultSymbol: {
            type: 'simple-line',
            color: [128, 128, 128, 0.8], // 灰色默认
            width: 3
          },
          uniqueValueInfos: [
            {
              value: '主干道',
              symbol: {
                type: 'simple-line',
                color: [255, 0, 0, 0.9], // 红色
                width: 6
              }
            },
            {
              value: '次干道',
              symbol: {
                type: 'simple-line',
                color: [255, 165, 0, 0.8], // 橙色
                width: 4
              }
            },
            {
              value: '支路',
              symbol: {
                type: 'simple-line',
                color: [255, 255, 0, 0.8], // 黄色
                width: 3
              }
            },
            {
              value: '步行道',
              symbol: {
                type: 'simple-line',
                color: [0, 255, 0, 0.8], // 绿色
                width: 2,
                style: 'dash'
              }
            },
            {
              value: '自行车道',
              symbol: {
                type: 'simple-line',
                color: [0, 191, 255, 0.8], // 天蓝色
                width: 2,
                style: 'dot'
              }
            },
            // 校园推荐路线样式
            {
              value: '去图书馆推荐路线',
              symbol: {
                type: 'simple-line',
                color: [138, 43, 226, 0.9], // 紫色
                width: 5,
                style: 'solid'
              }
            },
            {
              value: '去食堂推荐路线',
              symbol: {
                type: 'simple-line',
                color: [255, 20, 147, 0.9], // 深粉色
                width: 5,
                style: 'solid'
              }
            },
            {
              value: '去宿舍推荐路线',
              symbol: {
                type: 'simple-line',
                color: [30, 144, 255, 0.9], // 道奇蓝
                width: 5,
                style: 'solid'
              }
            },
            {
              value: '去教学楼推荐路线',
              symbol: {
                type: 'simple-line',
                color: [255, 140, 0, 0.9], // 深橙色
                width: 5,
                style: 'solid'
              }
            },
            {
              value: '去体育馆推荐路线',
              symbol: {
                type: 'simple-line',
                color: [50, 205, 50, 0.9], // 酸橙绿
                width: 5,
                style: 'solid'
              }
            },
            {
              value: '去实验楼推荐路线',
              symbol: {
                type: 'simple-line',
                color: [220, 20, 60, 0.9], // 深红色
                width: 5,
                style: 'solid'
              }
            },
            {
              value: '校园观光路线',
              symbol: {
                type: 'simple-line',
                color: [255, 215, 0, 0.9], // 金色
                width: 6,
                style: 'dash-dot'
              }
            },
            {
              value: '晨跑推荐路线',
              symbol: {
                type: 'simple-line',
                color: [0, 250, 154, 0.9], // 中春绿
                width: 4,
                style: 'dash'
              }
            }
          ]
        } as any,
        popupTemplate: {
          title: '道路信息',
          content: [
            {
              type: 'fields',
              fieldInfos: [
                { fieldName: 'name', label: '道路名称' },
                { fieldName: 'RoadType', label: '道路类型' },
                { fieldName: 'OBJECTID', label: 'ID' }
              ]
            }
          ]
        }
      })

      // 创建草图图层
      sketchLayer = new GraphicsLayer()

      // 创建地图
      const map = new Map({
        basemap: {
          baseLayers: [gaodeLayer],
        },
        layers: [buildingLayer, facilitiesLayer, roadsLayer, sketchLayer],
      })

      // 创建地图视图
      mapView = new MapView({
        container: mapDiv.value,
        map: map,
        zoom: 16,
        center: [116.79344073176162, 36.53820494873281], // 默认坐标，可修改为学校坐标
      })

      // 地图加载完成后解析 Promise
      mapView.when(async () => {
        resolve()
      })
    } else {
      // 如果没有 mapDiv，也需要解析 Promise 以避免阻塞
      resolve()
    }
  })
}

// 开始绘制点
const startDrawPoint = (mode: string) => {
  if (sketchViewModel) {
    currentEditMode.value = mode
    sketchLayer?.removeAll()
    sketchViewModel.create('point')
  }
}

// 开始绘制线
const startDrawPolyline = () => {
  if (sketchViewModel) {
    currentEditMode.value = 'road'
    sketchLayer?.removeAll()
    sketchViewModel.create('polyline')
  }
}

// 加载图层数据
const loadLayerData = async () => {
  try {
    if (!buildingLayer || !facilitiesLayer || !roadsLayer) {
      // 如果图层未初始化，先初始化地图
      initMap()
    }
    // 查询建筑物数据
    const buildingQuery = buildingLayer?.createQuery()
    if (buildingQuery) {
      buildingQuery.where = '1=1'
      const buildingResult = await buildingLayer?.queryFeatures(buildingQuery)
      console.log(buildingResult)
      if (buildingResult) {
        buildingList.value = buildingResult.features.map((feature) => ({
          id: feature.attributes.OBJECTID,
          name: feature.attributes.name,
          Buildingtype: feature.attributes.Buildingtype,
          description: feature.attributes.description,
        }))
      }
    }

    // 查询设施数据
    const facilitiesQuery = facilitiesLayer?.createQuery()
    if (facilitiesQuery) {
      facilitiesQuery.where = '1=1'
      const facilitiesResult = await facilitiesLayer?.queryFeatures(facilitiesQuery)
      if (facilitiesResult) {
        facilitiesList.value = facilitiesResult.features.map((feature) => ({
          id: feature.attributes.OBJECTID,
          name: feature.attributes.name,
          FacilitiesType: feature.attributes.FacilitiesType,
          description: feature.attributes.description,
        }))
      }
    }

    // 查询道路数据
    const roadsQuery = roadsLayer?.createQuery()
    if (roadsQuery) {
      roadsQuery.where = '1=1'
      const roadsResult = await roadsLayer?.queryFeatures(roadsQuery)
      if (roadsResult) {
        roadsList.value = roadsResult.features.map((feature) => ({
          id: feature.attributes.OBJECTID,
          name: feature.attributes.name,
          RoadType: feature.attributes.RoadType,
        }))
      }
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  }
}
await loadLayerData()
// 添加建筑物
const addBuilding = async () => {
  if (
    !buildingForm.name ||
    !buildingForm.Buildingtype ||
    !sketchBuilding // 检查是否有地理对象
  ) {
    ElMessage.warning('请填写完整信息并在地图上选择位置')
    return
  }

  try {
    // 如果图层未初始化，先初始化地图
    if (!buildingLayer) {
      await initMap()
    }

    // 确保图层已初始化
    if (!buildingLayer) {
      throw new Error('图层初始化失败')
    }

    const attributes = {
      name: buildingForm.name,
      Buildingtype: buildingForm.Buildingtype,
      description: buildingForm.description || '',
    }

    const graphic = new Graphic({
      geometry: sketchBuilding,
      attributes: attributes,
    })

    const result = await buildingLayer.applyEdits({
      addFeatures: [graphic],
    })

    if (result?.addFeatureResults?.[0]?.objectId) {
      ElMessage.success('添加建筑物成功')
      buildingDialogVisible.value = false
      // 重置表单
      Object.assign(buildingForm, {
        name: '',
        Buildingtype: '',
        description: '',
      })
      sketchBuilding = null // 重置地理对象
      // 重新加载数据
      await loadLayerData()
    } else {
      const error = result?.addFeatureResults?.[0]?.error || '未知错误'
      ElMessage.error(`添加建筑物失败: ${error}`)
    }
  } catch (error) {
    console.error('添加建筑物详细错误:', error)
    ElMessage.error('添加建筑物失败')
  }
}

// 添加设施
const addFacility = async () => {
  if (
    !facilitiesForm.name ||
    !facilitiesForm.FacilitiesType ||
    !sketchFacility // 检查是否有地理对象
  ) {
    ElMessage.warning('请填写完整信息并在地图上选择位置')
    return
  }
  // 如果图层未初始化，先初始化地图
  if (!facilitiesLayer) {
    await initMap()
  }

  try {
    const attributes = {
      name: facilitiesForm.name,
      FacilitiesType: facilitiesForm.FacilitiesType,
      description: facilitiesForm.description || '',
    }

    const graphic = new Graphic({
      geometry: sketchFacility,
      attributes: attributes,
    })

    const result = await facilitiesLayer?.applyEdits({
      addFeatures: [graphic],
    })

    if (result!.addFeatureResults[0].objectId) {
      ElMessage.success('添加设施成功')
      facilitiesDialogVisible.value = false
      // 重置表单
      Object.assign(facilitiesForm, {
        name: '',
        FacilitiesType: '',
        description: '',
      })
      sketchFacility = null // 重置地理对象
      // 重新加载数据
      await loadLayerData()
    } else {
      ElMessage.error('添加设施失败')
    }
  } catch (error) {
    console.error('添加设施失败:', error)
    ElMessage.error('添加设施失败')
  }
}

// 添加道路
const addRoad = async () => {
  if (!roadForm.name || !roadForm.RoadType || !sketchRoad) {
    ElMessage.warning('请填写完整信息并在地图上绘制路线')
    return
  }
  // 如果图层未初始化，先初始化地图
  if (!roadsLayer) {
    await initMap()
  }

  try {
    const attributes = {
      name: roadForm.name,
      RoadType: roadForm.RoadType,
    }

    const graphic = new Graphic({
      geometry: sketchRoad,
      attributes: attributes,
    })

    const result = await roadsLayer?.applyEdits({
      addFeatures: [graphic],
    })

    if (result?.addFeatureResults.length && result.addFeatureResults[0].objectId) {
      ElMessage.success('添加道路成功')
      roadDialogVisible.value = false
      // 重置表单
      Object.assign(roadForm, {
        name: '',
        RoadType: '',
      })
      sketchRoad = null // 重置地理对象
      // 重新加载数据
      await loadLayerData()
    } else {
      ElMessage.error('添加道路失败')
    }
  } catch (error) {
    console.error('添加道路失败:', error)
    ElMessage.error('添加道路失败')
  }
}

// 删除建筑物
const deleteBuilding = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该建筑物吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const result = await buildingLayer?.applyEdits({
      deleteFeatures: [{ objectId: id } as any],
    })

    if (result?.deleteFeatureResults.length && result.deleteFeatureResults[0].objectId) {
      ElMessage.success('删除建筑物成功')
      // 重新加载数据
      await loadLayerData()
    } else {
      ElMessage.error('删除建筑物失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除建筑物失败:', error)
      ElMessage.error('删除建筑物失败')
    }
  }
}

// 删除设施
const deleteFacility = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该设施吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const result = await facilitiesLayer?.applyEdits({
      deleteFeatures: [{ objectId: id } as any],
    })

    if (result?.deleteFeatureResults.length && result.deleteFeatureResults[0].objectId) {
      ElMessage.success('删除设施成功')
      // 重新加载数据
      await loadLayerData()
    } else {
      ElMessage.error('删除设施失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除设施失败:', error)
      ElMessage.error('删除设施失败')
    }
  }
}

// 删除道路
const deleteRoad = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该道路吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const result = await roadsLayer?.applyEdits({
      deleteFeatures: [{ objectId: id } as any],
    })

    if (result?.deleteFeatureResults.length && result.deleteFeatureResults[0].objectId) {
      ElMessage.success('删除道路成功')
      // 重新加载数据
      await loadLayerData()
    } else {
      ElMessage.error('删除道路失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除道路失败:', error)
      ElMessage.error('删除道路失败')
    }
  }
}

// 页面加载时初始化地图和加载数据
onMounted(async () => {
  await initMap()
  await loadLayerData()
})

// 初始化对话框中的地图
const initDialogMap = (container: HTMLDivElement) => {
  // 销毁旧的 sketchViewModel
  if (sketchViewModel) {
    sketchViewModel = null
  }

  // 销毁旧的地图视图
  if (dialogMapView) {
    dialogMapView = null
  }

  // 创建图层
  const tempBuildingLayer = new FeatureLayer({
    url: buildingLayerUrl,
    outFields: ['*'],
  })

  const tempFacilitiesLayer = new FeatureLayer({
    url: facilitiesLayerUrl,
    outFields: ['*'],
  })

  const tempRoadsLayer = new FeatureLayer({
    url: roadsLayerUrl,
    outFields: ['*'],
  })

  // 创建草图图层
  const tempSketchLayer = new GraphicsLayer()

  // 创建地图
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
    layers: [tempBuildingLayer, tempFacilitiesLayer, tempRoadsLayer, tempSketchLayer],
  })

  // 创建新的地图视图
  dialogMapView = new MapView({
    container: container,
    map: map,
    zoom: 16,
    center: [116.79344073176162, 36.53820494873281], // 默认坐标
  })

  // 创建草图视图模型
  dialogMapView.when(() => {
    sketchViewModel = new SketchViewModel({
      view: dialogMapView as __esri.MapView,
      layer: tempSketchLayer,
    })

    // 监听草图创建完成事件
    sketchViewModel.on('create', (event) => {
      if (event.state === 'complete') {
        const geometry = event.graphic.geometry
        tempSketchLayer.removeAll()
        // 根据当前编辑模式处理几何图形
        if (currentEditMode.value === 'building' && geometry!.type === 'point') {
          const point = geometry as __esri.Point
          sketchBuilding = point // 直接保存点对象

          // 在草图图层中显示
          const graphic = new Graphic({
            geometry: point,
            symbol: {
              type: 'simple-marker',
              color: [255, 0, 0, 0.8],
              size: 10,
              outline: {
                color: [255, 255, 255],
                width: 1,
              },
            } as any,
          })
          tempSketchLayer.add(graphic)
        } else if (currentEditMode.value === 'facility' && geometry!.type === 'point') {
          const point = geometry as __esri.Point
          sketchFacility = point // 直接保存点对象

          // 在草图图层中显示
          const graphic = new Graphic({
            geometry: point,
            symbol: {
              type: 'simple-marker',
              color: [0, 0, 255, 0.8],
              size: 10,
              outline: {
                color: [255, 255, 255],
                width: 1,
              },
            } as any,
          })
          tempSketchLayer.add(graphic)
        } else if (currentEditMode.value === 'road' && geometry!.type === 'polyline') {
          const polyline = geometry as __esri.Polyline
          sketchRoad = polyline // 直接保存线对象

          // 在草图图层中显示
          const graphic = new Graphic({
            geometry: polyline,
            symbol: {
              type: 'simple-line',
              color: [0, 255, 0, 0.8],
              width: 3,
            } as any,
          })
          tempSketchLayer.add(graphic)
        }
      }
    })
  })
}

// 修改对话框显示处理
const showBuildingDialog = () => {
  buildingDialogVisible.value = true
  // 重置地理对象
  sketchBuilding = null
  // 等待DOM更新后初始化地图
  setTimeout(() => {
    if (buildingMapDiv.value) {
      initDialogMap(buildingMapDiv.value)
    }
  }, 100)
}

const showFacilitiesDialog = () => {
  facilitiesDialogVisible.value = true
  // 重置地理对象
  sketchFacility = null
  // 等待DOM更新后初始化地图
  setTimeout(() => {
    if (facilitiesMapDiv.value) {
      initDialogMap(facilitiesMapDiv.value)
    }
  }, 100)
}

const showRoadDialog = () => {
  roadDialogVisible.value = true
  // 重置地理对象
  sketchRoad = null
  // 等待DOM更新后初始化地图
  setTimeout(() => {
    if (roadMapDiv.value) {
      initDialogMap(roadMapDiv.value)
    }
  }, 100)
}

// 退出登录功能
const logout = () => {
  userStore.clearUserInfo()
  ElMessage.success('退出登录成功')
  router.push('/login')
}
</script>

<template>
  <div class="admin-container">
    <div ref="mapDiv" style="width: 0%; height: 0%"></div>
    <el-card class="admin-card">
      <template #header>
        <div class="card-header">
          <h2>数据管理</h2>
          <el-button type="danger" @click="logout" size="small">退出登录</el-button>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <!-- 建筑物管理 -->
        <el-tab-pane label="建筑物管理" name="building">
          <div class="action-bar">
            <el-button type="primary" @click="showBuildingDialog">添加建筑物</el-button>
          </div>

          <el-table :data="buildingList" style="width: 100%" border>
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="建筑名称" />
            <el-table-column prop="Buildingtype" label="建筑类型" />
            <el-table-column prop="description" label="建筑描述" />
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button type="danger" size="small" @click="deleteBuilding(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 设施管理 -->
        <el-tab-pane label="设施管理" name="facilities">
          <div class="action-bar">
            <el-button type="primary" @click="showFacilitiesDialog">添加设施</el-button>
          </div>

          <el-table :data="facilitiesList" style="width: 100%" border>
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="设施名称" />
            <el-table-column prop="FacilitiesType" label="设施类型" />
            <el-table-column prop="description" label="设施描述" />
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button type="danger" size="small" @click="deleteFacility(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 道路管理 -->
        <el-tab-pane label="道路管理" name="roads">
          <div class="action-bar">
            <el-button type="primary" @click="showRoadDialog">添加道路</el-button>
          </div>

          <el-table :data="roadsList" style="width: 100%" border>
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="道路名称" />
            <el-table-column prop="RoadType" label="道路类型" />
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button type="danger" size="small" @click="deleteRoad(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加建筑物对话框 -->
    <el-dialog v-model="buildingDialogVisible" title="添加建筑物" width="800px">
      <div class="dialog-content">
        <div class="map-container">
          <div ref="buildingMapDiv" class="map"></div>
          <div class="map-tools">
            <el-button type="primary" @click="startDrawPoint('building')">在地图上选点</el-button>
          </div>
        </div>
        <el-form :model="buildingForm" label-width="100px">
          <el-form-item label="建筑名称">
            <el-input v-model="buildingForm.name" />
          </el-form-item>
          <el-form-item label="建筑类型">
            <el-select v-model="buildingForm.Buildingtype" placeholder="请选择建筑类型">
              <el-option label="教学楼" value="教学楼" />
              <el-option label="宿舍楼" value="宿舍楼" />
              <el-option label="图书馆" value="图书馆" />
              <el-option label="食堂" value="食堂" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
          <el-form-item label="建筑描述">
            <el-input v-model="buildingForm.description" type="textarea" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="buildingDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addBuilding">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加设施对话框 -->
    <el-dialog v-model="facilitiesDialogVisible" title="添加设施" width="500px">
      <div class="dialog-content">
        <div class="map-container">
          <div ref="facilitiesMapDiv" class="map"></div>
          <div class="map-tools">
            <el-button type="primary" @click="startDrawPoint('facility')">在地图上选点</el-button>
          </div>
        </div>
        <el-form :model="facilitiesForm" label-width="100px">
          <el-form-item label="设施名称">
            <el-input v-model="facilitiesForm.name" />
          </el-form-item>
          <el-form-item label="设施类型">
            <el-select v-model="facilitiesForm.FacilitiesType" placeholder="请选择设施类型">
              <el-option label="设施" value="设施" />
              <el-option label="自行车停放点" value="自行车停放点" />
              <el-option label="商店" value="商店" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
          <el-form-item label="设施描述">
            <el-input v-model="facilitiesForm.description" type="textarea" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="facilitiesDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addFacility">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加道路对话框 -->
    <el-dialog v-model="roadDialogVisible" title="添加道路" width="800px">
      <div class="dialog-content">
        <div class="map-container">
          <div ref="roadMapDiv" class="map"></div>
          <div class="map-tools">
            <el-button type="primary" @click="startDrawPolyline">在地图上绘制路线</el-button>
          </div>
        </div>
        <el-form :model="roadForm" label-width="100px">
          <el-form-item label="道路名称">
            <el-input v-model="roadForm.name" />
          </el-form-item>
          <el-form-item label="道路类型">
            <el-select v-model="roadForm.RoadType" placeholder="请选择道路类型">
              <el-option-group label="基础道路类型">
                <el-option label="主干道" value="主干道" />
                <el-option label="人行道" value="人行道" />
                <el-option label="自行车道" value="自行车道" />
                <el-option label="其他" value="其他" />
              </el-option-group>
              <el-option-group label="校园推荐路线">
                <el-option label="去图书馆推荐路线" value="去图书馆推荐路线" />
                <el-option label="去食堂推荐路线" value="去食堂推荐路线" />
                <el-option label="去宿舍推荐路线" value="去宿舍推荐路线" />
                <el-option label="去教学楼推荐路线" value="去教学楼推荐路线" />
                <el-option label="去体育馆推荐路线" value="去体育馆推荐路线" />
                <el-option label="去实验楼推荐路线" value="去实验楼推荐路线" />
                <el-option label="校园观光路线" value="校园观光路线" />
                <el-option label="晨跑推荐路线" value="晨跑推荐路线" />
              </el-option-group>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roadDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addRoad">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.admin-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.admin-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-bar {
  margin-bottom: 20px;
}

.point-item {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.dialog-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.map-container {
  width: 100%;
  height: 300px;
  position: relative;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.map {
  width: 100%;
  height: 100%;
}

.map-tools {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 10;
}
</style>
